package com.jxcq.tensquare.friend.controller;

import com.jxcq.tensquare.friend.client.UserClient;
import com.jxcq.tensquare.friend.service.FriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("friend")
public class FriendController {

  @Autowired
  private HttpServletRequest request;

  @Autowired
  private FriendService friendService;

  @Autowired
  private UserClient userClient;


  @DeleteMapping("{friendid}")
  public Result deleteFriend(@PathVariable String friendid){
    //验证是否登录，并且拿到当前登录用户id
    Claims claims =  (Claims)request.getAttribute("claims_user");
    if(claims == null){
      //说明当前用户没有user角色
      return new Result(false, StatusCode.LOGIN_ERROR,"权限不足");
    }
    //当道当前登录用户id
    String userid = claims.getId();

    friendService.deleteFriend(userid,friendid);
    userClient.updatefasnscountfollowcount(userid,friendid,-1);
    return new Result(true, StatusCode.SUCCESS,"删除成功");
  }

  /**
   * 添加好友或添加非好友
   * @return
   */
  @PutMapping("like/{friengid}/{type}")
  public Result addFriend(@PathVariable String friendid, @PathVariable String type){
    //验证是否登录，并且拿到当前登录用户id
    Claims claims =  (Claims)request.getAttribute("claims_user");
    if(claims == null){
      //说明当前用户没有user角色
      return new Result(false, StatusCode.LOGIN_ERROR,"权限不足");
    }
    //当道当前登录用户id
    String userid = claims.getId();

    //判断是添加好友还是添加非好友
    if(StringUtils.equals("1",type)){
        //添加好友
      int flag = friendService.addFriend(userid,friendid);
      if(flag == 0){
        return new Result(false, StatusCode.REPEAT_ERROR,"不能重复添加好友");
      }
      if(flag == 1){
        userClient.updatefasnscountfollowcount(userid,friendid,1);
        return new Result(true, StatusCode.SUCCESS,"添加成功");
      }
    }
    if(StringUtils.equals("2",type)){
      //添加非好友
      int flag = friendService.addNoFriend(userid,friendid);
      if(flag == 0){
        return new Result(false, StatusCode.REPEAT_ERROR,"不能重复添加非好友");
      }
      if(flag == 1){
        return new Result(true, StatusCode.SUCCESS,"添加成功");
      }
    }
    return new Result(false, StatusCode.FAILE,"参数异常");
  }

}
